import re,collections
alphabet='abcdefghijklmnopqrstuvwxyz'
#使用正则表达式，提取出来单词，把单词转成小写。
def words(text):
    return re.findall('[a-z]+',text.lower())
#算单词出现的次数
def train(feature):
    model=collections.defaultdict(lambda :1)
    for f in feature:
        model[f]+=1
    return model
#返回所有与单词w编辑距离为1的集合，增删改查
def edits1(word):
    n = len(word)
    return set([word[0:i]+word[i+1:]for i in range(n)]+                     # 删除
               [word[0:i]+word[i+1]+word[i]+word[i+2:]for i in range(n-1)]+# 相互移位
               [word[0:i]+c+word[i+1:]for i in range(n)for c in alphabet]+# 改变一个字母
               [word[0:i]+c+word[i:]for i in range(n+1)for c in alphabet])  # 插入一个字母

def known_edits2(word):
    return set(e2 for e1 in edits1(word)for e2 in edits1(e1)if e2 in NWORDS)

def known(words):return set(w for w in words if w in NWORDS)

def correct(word):
    candidates = known([word])or known(edits1(word))or known_edits2(word)or[word]
    return max(candidates, key=lambda w: NWORDS[w])
#获得出现的频率
NWORDS =train(words(open('rich_father.txt').read()))

def main():
    while True:
        word=input('请输入单词')
        word1=correct(word)
        if(word!=word1):
            print('you want input :'+word1+' ?')
        else:
            print('right!')


if __name__=='__main__':
    main()